const dbUtil = require('../util/dbutil')
const {
    AssertUtils
} = require('../util/utils')
const fs = require('fs');
const path = require('path');
const changeSqlRelyOn = (data) => {
    const keyArr = ['fan', 'car_lock', 'window_trunk', 'flash_light', 'stir_up_trouble', 'air_conditioning', 'flashingLights_whistling', 'charging_state']
    return {
        sql: Object.keys(data).filter(key => keyArr.includes(key)).map(key => `${key}=?`).join(','),
        valueData: Object.keys(data).filter(key => keyArr.includes(key)).map(key => data[key]),
        car_id: data['id']
    }

}
/**
 * 查询用户所有车辆信息
 * @param {string} id 用户ID
 * @returns 
 */
const getCardByUserList = async (userId) => {
    return dbUtil.getAll(`SELECT 
    c.id , c.user_id , c.km_kw , c.battery_level , c.license_plate , c.vehicle_model , ci.charging_state ,
    ci.fan , ci.car_lock , ci.window_trunk , ci.flash_light , ci.stir_up_trouble , ci.air_conditioning , ci.flashingLights_whistling 
        FROM  car c 
    INNER JOIN car_info ci ON c.id = ci.car_id WHERE c.user_id=?`, [userId,])
}
/**
 * 查询车辆信息
 * @param {string} id 用户ID
 * @returns 
 */
const getCardInfo = async (id, pageNum = 1, pageSize = 10) => {
    const result = await dbUtil.getAll(`SELECT 
    c.id , c.user_id , c.km_kw , c.battery_level , c.license_plate , c.vehicle_model , ci.charging_state ,
    ci.fan , ci.car_lock , ci.window_trunk , ci.flash_light , ci.stir_up_trouble , ci.air_conditioning , ci.flashingLights_whistling 
        FROM  car c 
    INNER JOIN car_info ci ON c.id = ci.car_id WHERE c.user_id=? LIMIT ? OFFSET ?`, [id, parseInt(pageSize), parseInt(pageNum - 1) * parseInt(pageSize),])
    return await Promise.all(result.map(async item => {
        item.userInfo = await dbUtil.getRow(`select * from user where id = ?`, [item.user_id])
        return item
    }))
}

const getChangeCarInfo = async (data, userId) => {
    let count = await dbUtil.getCount(`SELECT count(1) FROM car WHERE id = ${data.id} AND user_id = ${userId}`)
    AssertUtils.isTrue(count != 0, "车辆不存在")
    const {
        sql,
        valueData,
        car_id
    } = changeSqlRelyOn(data)
    return await dbUtil.exec(`UPDATE car_info
    SET ${sql}
    WHERE car_id = ${car_id}`, valueData)
}
const getCardList = async () => {
    const result = await dbUtil.getAll(`SELECT * FROM car`)
    return await Promise.all(result.map(async item => {
        item.info = await dbUtil.getRow(`SELECT * FROM car_info where car_id=${item.id}`)
        return item
    }))
}
const getReverseImage = () => {
    const directoryPath = path.join(path.dirname(__dirname), 'public', 'resource', 'uploads', 'car')
    return fs.readdirSync(directoryPath).map(item => path.join('resource', 'uploads', 'car', item))
}
module.exports = {
    getCardInfo,
    getChangeCarInfo,
    getCardList,
    getCardByUserList,
    getReverseImage
}